package com.u17;

/**
 * @author u17
 * https://leetcode-cn.com/problems/length-of-last-word/
 */
public class Solution {

    public int lengthOfLastWord(String s) {
        System.out.println(s.length());
        String [] str = s.split(" ");
        return str[str.length - 1].length();
    }

    /**
     * 改进
     * @param s
     * @return
     */
    public int lengthOfLastWord2(String s) {
        int i = s.length() - 1;
        int count = 0;
        // 找出最后的单词
        for (; i >= 0; i--) {
            // 去掉字符串末尾的空
            if (s.charAt(i) != ' ') {
                break;
            }
        }

        // 现在i的下表就是字符串的最后一个字母的下表
        for (; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                count++;
            } else {
                break;
            }
        }
        return count;
    }


    public static void main(String[] args) {
        String s = "luffy is still joyboy    ";
        Solution solution = new Solution();
        System.out.println(solution.lengthOfLastWord2(s));
    }
}
